from flask import Flask, render_template
import json
from pathlib import Path

app = Flask(__name__)

# 获取最新预测文件路径
def get_latest_prediction_file():
    pred_dir = Path(__file__).parent.parent / 'predictions'
    pattern = 'offline_7days_*.json'
    latest_file = None
    latest_time = 0
    
    for file in pred_dir.glob(pattern):
        # 从文件名提取时间戳部分
        timestamp_str = file.stem.split('_')[-1]
        try:
            timestamp = int(timestamp_str)
            if timestamp > latest_time:
                latest_time = timestamp
                latest_file = file
        except ValueError:
            continue
            
    return latest_file

# 加载并验证预测数据
def load_predictions():
    try:
        data_path = get_latest_prediction_file()
        if not data_path:
            raise FileNotFoundError("No prediction files found")
            
        with open(data_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        if not data or not isinstance(data, list):
            raise ValueError("Invalid data format: expected list of predictions")
            
        # 从第一条数据中提取污染物键名(排除非污染物字段)
        required_keys = {'timestamp', 'prediction_type', 'hours_ahead'}
        pollutants = [k for k in data[0].keys() if k not in required_keys]
        
        # 验证所有数据项都有相同的结构
        for i, pred in enumerate(data):
            if not all(k in pred for k in pollutants):
                raise ValueError(f"Missing keys in prediction item {i}")
                
        return data, pollutants
        
    except Exception as e:
        app.logger.error(f"Error loading predictions: {str(e)}")
        return [], []

@app.route('/')
def dashboard():
    predictions, pollutants = load_predictions()
    return render_template('index.html',
                         predictions=predictions,
                         pollutants=pollutants)

if __name__ == '__main__':
    app.run(debug=True)